package com.example.evennews.view

import androidx.compose.ui.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column


import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.traceEventEnd
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.Coil
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.util.CoilUtils

import com.example.evennews.R
import com.example.evennews.bean.NewsDigest
import com.example.evennews.bean.NewsItem
import com.example.evennews.bean.NewsType
import com.example.evennews.view.ui.theme.BlackText
import com.example.evennews.view.ui.theme.EvenNewsTheme
import com.example.evennews.view.ui.theme.GrayText
import com.example.evennews.view.ui.theme.Pink40
import com.example.evennews.viewmodel.DetailStatus

import com.example.evennews.viewmodel.DigestStatus
import com.example.evennews.viewmodel.NewsViewmodel
import com.example.evennews.viewmodel.TypeStatus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class NewsActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            EvenNewsTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    AppPage()

                }
            }
        }

    }
}


@Composable
fun AppPage(modifier: Modifier = Modifier) {
    val viewmodel = viewModel<NewsViewmodel>()
    val typeStatus by viewmodel.typeStatus.observeAsState(TypeStatus.LOADING)
    val digestStatus by viewmodel.digestStatus.observeAsState(DigestStatus.LOADING)

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .background(Color.Gray), horizontalAlignment = Alignment.CenterHorizontally
    ) {
        //typeStatus加载成功之后不会再变化
        when (typeStatus) {
            TypeStatus.LOADING -> {
                viewmodel.getNewsType()
                LoadingAttention("新闻类目加载中……")
            }

            TypeStatus.SUCCEED -> {
                ChannelType(
                    viewmodel,
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight(0.1f)
                        .background(Color.Yellow),
                )
                when (digestStatus) {
                    DigestStatus.LOADING -> {
                        Spacer(modifier = Modifier.height(25.dp))
                        LoadingAttention("新闻列表加载中……")
                    }

                    DigestStatus.SUCCEED -> {

                        NewsList(
                            viewmodel, modifier = Modifier
                                .fillMaxWidth()
                                .fillMaxHeight()
                        )
                    }

                    DigestStatus.FAILED -> {
                        FailureAttention("新闻列表加载失败，检查网络或点击重试") {
                            var typeindex = viewmodel.currentType.value ?: 1
                            if (typeindex < 0) typeindex = 0
                            viewmodel.chooseType(typeindex)
                        }
                    }
                }


            }

            TypeStatus.FAILED -> {
                Spacer(modifier = Modifier.height(25.dp))
                FailureAttention(
                    "新闻类别加载失败，检查网络或点击重试"
                ) {
                    viewmodel.getNewsType()
                }
            }
        }

    }

    NewsDetailPage(viewmodel, modifier = Modifier) { viewmodel.closeNewsDetail() }


}

@Composable
fun FailureAttention(msg: String, onRetry: () -> Unit) {
    Box(
        Modifier
            .clip(RoundedCornerShape(8.dp))
            .background(Color.White)

            .fillMaxWidth(0.85f)
            .padding(15.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
//            val vectorImageResource: ImageVector = vectorResource(id = R.drawable.example_vector)
//            val vectorPainter = rememberVectorPainter(image = vectorImageResource)
            Text(text = msg)
            Image(painter = painterResource(id = R.drawable.baseline_refresh_24),
                contentDescription = "", contentScale = ContentScale.Crop,
                modifier = Modifier
                    .fillMaxWidth(0.2f)
                    .clickable {
                        onRetry()
                    })

        }
    }
}

@Composable
fun LoadingAttention(msg: String) {
    Box(
        Modifier
            .clip(RoundedCornerShape(8.dp))
            .background(Color.White)
            .height(50.dp)
            .fillMaxWidth(0.85f)
            .padding(15.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(text = msg)

    }
}

@Composable
fun NewsDetailPage(viewmodel: NewsViewmodel, modifier: Modifier, onBack: () -> Unit) {
    val detailStatus by viewmodel.detailStatus.observeAsState(DetailStatus.CLOSED)
    val digest by viewmodel.currentDigest.observeAsState(
        NewsDigest(
            "类别ID", "标题", "新闻概要",
            "新闻ID", "来源", "发布时间"
        )
    )
    val items by viewmodel.newsItemList.observeAsState(initial = emptyList())
    if (detailStatus != DetailStatus.CLOSED) {
        Card(
            Modifier
                .fillMaxSize()
                .background(Pink40)

        ) {
            Image(
                painter = painterResource(id = R.drawable.baseline_arrow_back_24),
                contentDescription = "",
                Modifier
                    .padding(10.dp)
                    .clickable { onBack() }
            )
            LazyColumn(
                Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                item {
                    Text(
                        text = digest.title,
                        Modifier
                            .fillMaxWidth(0.9f)
                            .align(Alignment.CenterHorizontally),
                        fontWeight = FontWeight.Bold,
                        color = BlackText,
                        textAlign = TextAlign.Center,
                        fontSize = 25.sp
                    )
                    Text(
                        text = "发布时间:" + digest.postTime,
                        Modifier
                            .fillMaxWidth(0.8f),
                        fontSize = 10.sp,
                        color = GrayText,
                        textAlign = TextAlign.Center
                    )
                    Text(
                        text = "来源:" + digest.source,
                        Modifier
                            .fillMaxWidth(0.95f)
                            .align(Alignment.CenterHorizontally), fontSize = 10.sp,
                        color = GrayText,
                        textAlign = TextAlign.End
                    )
                    Spacer(modifier = Modifier.height(25.dp))
                }

                Log.d("TAG", "NewsDetailPage: detailStatus=" + detailStatus)
                when (detailStatus) {
                    DetailStatus.OPENED_PRELOAD -> {
                        //多一个状态，不然第一次进去加载不出新闻详情
                        viewmodel.detailReadyLoading()
                    }

                    DetailStatus.OPENED_LOADING -> {

                        item {
                            LoadingAttention(msg = "新闻详情加载中……")
                            viewmodel.getNewsDetailItems(digest.newsId)
//                            LaunchedEffect(Unit) {
//                                val list = viewmodel.getNewsItems(digest.newsId).await()
//
//                                list?.let {
//                                    withContext(Dispatchers.Main) {
//                                        Log.d("TAG", "NewsDetailPage: loading" + it.toString())
//                                        items.value = it
//                                    }
//                                }
//                            }
                        }
                    }

                    DetailStatus.OPENED_SUCCEED -> {
//                        Log.d("TAG", "NewsDetailPage: succeed" + items.toString())
                        repeat(items.size) { index ->
                            item {
                                NewsDetails(
                                    items[index]
                                )
                            }
                        }

                    }

                    DetailStatus.OPENED_FAILED -> {
                        item {
                            FailureAttention(
                                "新闻详情加载失败，检查网络或点击重试"
                            ) {
                                viewmodel.onRetryDetailItems()
                            }
                        }

                    }

                    else -> {}
                }

                item {
                    Spacer(
                        modifier = Modifier
                            .height(100.dp)
                            .fillMaxWidth()
                    )
                }

            }


        }
    }

}


@Composable
fun NewsDetails(item: NewsItem) {
    Column {
        when (item.type) {
            "text" -> {
              //  Log.d(TAG, "NewsDetails: ")
                Text(
                    text = "    " + item.content, Modifier
                        .fillMaxWidth(0.9f)
                )
            }

            "img" -> {
                Log.d("TAG", "NewsDetails: "+item.imageUrl)
                AsyncImage(
                    model = item.imageUrl,
                    onError = {
                        Log.d("TAG", "image error ")
                        it.result.throwable.printStackTrace()
                              },
                    onLoading = { Log.d("TAG", "image loading ")},
                    onSuccess = {Log.d("TAG", "image success ")},
                    contentDescription = "",
                    modifier = Modifier.fillMaxWidth(0.9f),
                    contentScale = ContentScale.Crop,
                    placeholder = painterResource(id = R.drawable.ic_launcher_background)
                )
            }

            "video" -> {

            }
        }
        Spacer(modifier = Modifier.height(10.dp))
    }

}

@Composable
fun NewsList(viewmodel: NewsViewmodel, modifier: Modifier) {
    val list by viewmodel.newsDigestList.observeAsState(initial = emptyList())
    val page by viewmodel.currentPage.observeAsState(1)
    LazyColumn(
        modifier, horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        repeat(list.size) {
            val digest = list[it]
            item {
                NewsDigestItem(
                    digest = digest,
                    modifier = Modifier.padding(10.dp, 10.dp)
                ) { chosenDigest ->
                    viewmodel.openNewsDetail(it)
                }
            }
        }

        item {
            Spacer(modifier = Modifier.height(20.dp))
            PageController(page,
                { //上一页
                    if (page > 1) {
                        viewmodel.turnPage(page - 1)
                    }
                }, {
                    //下一页
                    viewmodel.turnPage(page + 1)
                })
        }
    }

}

@Composable
fun PageController(page: Int, onClickLastPage: () -> Unit, onClickNextPage: () -> Unit) {
    Row {
        Button(onClick = { onClickLastPage() }, enabled = page > 1) {
            Text(text = "上一页")
        }
        Text(
            text = "第" + page + "页",
            Modifier
                .padding(10.dp)
                .align(Alignment.CenterVertically)
        )
        Button(onClick = {
            onClickNextPage()
        }, enabled = true) {
            Text(text = "下一页")
        }
    }
}

@Composable
fun NewsDigestItem(digest: NewsDigest, modifier: Modifier, onClick: (NewsDigest) -> Unit) {
    Box(
        Modifier
            .padding(5.dp)
            .clip(RoundedCornerShape(8.dp))
            .fillMaxWidth(0.9f)
            .background(Color.White)
            .clickable { onClick(digest) }
    ) {
        Column(Modifier.padding(5.dp)) {
            Text(
                text = "发布时间:" + digest.postTime,
                Modifier
                    .fillMaxWidth(0.8f),
                fontSize = 10.sp,
                color = GrayText,
                textAlign = TextAlign.Center
            )
            Spacer(modifier = Modifier.height(10.dp))
            Text(
                text = digest.title,
                Modifier
                    .fillMaxWidth(0.9f)
                    .align(Alignment.CenterHorizontally),
                fontWeight = FontWeight.Bold,
                color = BlackText,
                fontSize = 20.sp
            )
            Text(
                text = digest.digest,
                Modifier
                    .fillMaxWidth(0.8f)
                    .align(Alignment.CenterHorizontally),
                fontSize = 15.sp,
                color = GrayText,
                maxLines = 3
            )
            Spacer(modifier = Modifier.height(20.dp))
            Text(
                text = "来源:" + digest.source,
                Modifier
                    .fillMaxWidth(0.95f)
                    .align(Alignment.CenterHorizontally), fontSize = 10.sp,
                color = GrayText,
                textAlign = TextAlign.End
            )
            Spacer(modifier = Modifier.height(50.dp))

        }
    }
}

@Composable
fun ChannelType(viewmodel: NewsViewmodel, modifier: Modifier) {
    val typeslist by viewmodel.newsTypeStateFlow.observeAsState(emptyList())
    val currentType by viewmodel.currentType.observeAsState(0)
    LazyRow(modifier, verticalAlignment = Alignment.CenterVertically) {
        repeat(typeslist.size) { index ->
            val type = typeslist[index]
            item {


                TypeItem(
                    index == currentType,
                    type = type,
                    modifier = Modifier.padding(10.dp),
                    onClick = {
                        viewmodel.chooseType(index)
                    }
                )
            }

        }
    }

}

@Composable
fun TypeItem(ischoosen: Boolean, type: NewsType, modifier: Modifier, onClick: () -> Unit) {

    Box(
        modifier = modifier
            .fillMaxWidth(0.12f)
            .clickable {
                onClick()
            },

        ) {
        Text(
            text = type.typeName, Modifier,
            color = if (ischoosen) BlackText else GrayText,
            fontSize = if (ischoosen) 20.sp else 15.sp,
        )
    }

}


@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    EvenNewsTheme {
        AppPage()
    }

}